package com.other;

import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CookieStore;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCookieStore;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.impl.cookie.BasicClientCookie;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * Created by baiguantao on 2017/6/13.
 * http线程池管理
 */
public class HttpUtils {
    private static PoolingHttpClientConnectionManager clientConnectionManager = null;
//    private static RequestConfig requestConfig = RequestConfig.DEFAULT;
    private static   RequestConfig requestConfig = null;

    private static HttpClient httpClient = HttpClients.createDefault();
    {
        requestConfig=RequestConfig.custom().setConnectTimeout(5000).setConnectionRequestTimeout(1000)
                .setSocketTimeout(5000).build();
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", SSLConnectionSocketFactory.getSocketFactory())
                .register("http", PlainConnectionSocketFactory.getSocketFactory())
                .build();
        clientConnectionManager=new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        clientConnectionManager.setMaxTotal(50);
        clientConnectionManager.setDefaultMaxPerRoute(25);
        CookieStore cookieStore = new BasicCookieStore();
        BasicClientCookie cookie = new BasicClientCookie("sessionID", "######");
        cookie.setDomain("#####");
        cookie.setPath("/");
        cookieStore.addCookie(cookie);
        HttpClients.custom().setConnectionManager(clientConnectionManager).setDefaultCookieStore(cookieStore).setDefaultRequestConfig(requestConfig).build();
    }

    public static String post2(String url, String ext) {

        System.out.println("send request url -> " + url);
        System.out.println("send request params -> " + ext);
        String result = null;
        try {
            result = postSendHttp(url, ext);
        } catch (Exception e) {
            System.out.println("post error"+ e);
        }
        System.out.println("receive response --> " + result);
        return result.toString();
    }
    /**
     * 发送post请求
     * @param url
     * @param body
     * @return
     */
    private static String postSendHttp(String url, String body) {
         System.out.println("请求[参数] - " + body);
        long start = System.currentTimeMillis();
        if (url == null || "".equals(url)) {
            System.out.println("request url is empty.");
            return null;
        }
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        post.setHeader("Content-Type", "application/x-www-form-urlencoded;charset=utf-8");
        String resultString = null;
        try {
            StringEntity stringEntity = new StringEntity(body, "UTF-8");
            stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_ENCODING, "UTF-8"));
            // 设置请求主体
            post.setEntity(stringEntity);
            // 发起交易
            HttpResponse resp = httpClient.execute(post);
            int ret = resp.getStatusLine().getStatusCode();
            if (ret == HttpStatus.SC_OK) {
                // 响应分析
                HttpEntity entity = resp.getEntity();

                BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                StringBuffer responseString = new StringBuffer();
                String result = br.readLine();
                while (result != null) {
                    responseString.append(result);
                    result = br.readLine();
                }
                long end = System.currentTimeMillis();
                 System.out.println("请求[" + url + "]消耗时间 " + (end - start) + "毫秒");
                resultString = responseString.toString();
                 System.out.println("响应内容 - " + resultString);
            } else {
                 System.out.println("响应状态码- " + ret);
            }
        } catch (ClientProtocolException e) {
             System.out.println("Post ClientProtocolException"+ e);
        } catch (IOException e) {
             System.out.println("Post IOException"+e);
        } finally {
            // 释放连接
            post.releaseConnection();
        }
        return resultString;
    }

    /**
     * get请求
     * @param url
     * @param param
     * @return
     */
    public static String sendGet(String url, String param) {
        if (url == null || "".equals(url)) {
            System.out.println("request url is empty.");
            return null;
        }
        String rquestUrl = url;
        try {
            if (StringUtils.isNotBlank(param)) {
                if (url.indexOf("?") != -1) {
                    rquestUrl += "&" + param;
                } else {

                    rquestUrl += "?" + param;
                }
            }
            return sendGetHttp(rquestUrl);
        } catch (Exception e) {
             System.out.println("send post with https error -> " + e);
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 发送get请求
     * @param url
     * @return
     */
    private static String sendGetHttp(String url) {
        long start = System.currentTimeMillis();
        HttpGet get = new HttpGet(url);
        get.setConfig(requestConfig);
        String resultString = null;
        try {
            // 用get方法发送http请求
             System.out.println("执行get请求:...." + url);
            HttpResponse resp = httpClient.execute(get);
            int ret = resp.getStatusLine().getStatusCode();
            if (ret == HttpStatus.SC_OK) {
                // 响应分析
                HttpEntity entity = resp.getEntity();

                BufferedReader br = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
                StringBuffer responseString = new StringBuffer();
                String result = br.readLine();
                while (result != null) {
                    responseString.append(result);
                    result = br.readLine();
                }
                long end = System.currentTimeMillis();
                 System.out.println("请求[" + url + "]消耗时间 " + (end - start) + "毫秒");
                resultString = responseString.toString();
                 System.out.println("响应内容 - " + resultString);
            } else {
                 System.out.println("响应状态码- " + ret);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 释放连接
            get.releaseConnection();
        }
        return resultString;
    }

    public static void main(String[] args) {
        String url="http://localhost:8011/360/api/userImage360";
        String ext="name=xx";
        HttpUtils.post2(url,ext);
        HttpUtils.sendGetHttp("http://210.38.208.158:8081/ds/rest/tzhxyapi/get _deltakcxx");
    }
}
